<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理系统</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src="./js/jquery-3.7.1.js"></script>
    <style>
        /* 添加页面样式 */
        #addProductForm {
            display: none; /* 默认隐藏 */
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            z-index: 1000; /* 确保在其他内容之上 */
            width: 400px;
            padding: 20px;
            background-color: #ffffff;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        }

        .form-group {
            margin-bottom: 15px;
        }

        /* 添加遮罩层样式 */
        #overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: 100vw;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <!-- 标题 -->
    <div class="row">
        <div class="col-md-12">
            <h1 class="text-center">商品管理系统</h1>
        </div>
    </div>
    <!-- 搜索 -->
    <div class="row">
        <div class="form-row col-md-8">
            <div class="col">
                <input type="text" id="productName" class="form-control" placeholder="商品名称">
            </div>
        </div>
        <div class="col-md-4">
            <button type="button" class="btn btn-primary">搜索</button>
            <script>
                $(function () {
                    const $productNameInput = $('#productName');

                    $('button').click(function () {
                        const $btn = $(this);
                        if ($btn.data('loading')) return;
                        $btn.data('loading', true);

                        const productName = $productNameInput.val();

                        const requestUrl = `http://localhost:8080/products?keyword=${productName}`;
                        $.ajax({
                            url: requestUrl,
                            type: 'get',
                            dataType: 'json',
                            success: function (res) {
                                console.log('返回的数据:', res);
                                $('tbody').empty();
                                var products = res.data;
                                products.forEach(function (product) {
                                    var tr = '<tr>' +
                                        '<th scope="row">' + product.productId + '</th>' +
                                        '<td>' + product.productName + '</td>' +
                                        '<td>' + product.typeName + '</td>' +
                                        '<td>' + product.price + '</td>' +
                                        '<td>' +
                                        '<button type="button" class="btn btn-primary">修改</button>' +
                                        '<button type="button" class="btn btn-danger">删除</button>' +
                                        '</td>' +
                                        '</tr>';
                                    $('tbody').append(tr);
                                });
                            },
                            error: function (xhr, status, error) {
                                console.error('请求失败:', error);
                                alert('请求失败，请稍后再试');
                            },
                            complete: function () {
                                $btn.data('loading', false); // 重置按钮状态
                            }
                        });
                    });
                });
            </script>

            <button type="button" class="btn btn-primary" id="addProductBtn">添加</button>

            <!-- 添加表单模态框 -->
            <div id="overlay"></div>
            <div id="addProductForm">
                <h3>添加新商品</h3>
                <div class="form-group">
                    <label for="newProductName">商品名称:</label>
                    <input type="text" id="newProductName" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="newType">商品类型:</label>
                    <select id="newType" class="form-control" required>
                        <script>
                            $(function () {
                                $.ajax({
                                    url: 'http://localhost:8080/product-types',
                                    type: 'get',
                                    dataType: 'json',
                                    success: function (res) {
                                        var types = res.data;
                                        types.forEach(function (type) {
                                            var option = '<option value="' + type.typeId + '">' + type.typeName + '</option>';
                                            $('#newType').append(option);
                                        });
                                        $('#newType option:first').prop('selected', true);
                                    }
                                });
                            });
                        </script>
                    </select>
                </div>
                <div class="form-group">
                    <label for="newPrice">价格:</label>
                    <input type="number" id="newPrice" class="form-control" step="0.01" required>
                </div>
                <div class="form-group">
                    <label for="newStock">库存:</label>
                    <input type="number" id="newStock" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="newStatus">状态:</label>
                    <select id="newStatus" class="form-control" required>
                        <option value="active">上架</option>
                        <option value="inactive">下架</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="newDescription">描述:</label>
                    <textarea id="newDescription" class="form-control"></textarea>
                </div>
                <div class="form-group">
                    <button type="button" class="btn btn-success">提交</button>
                    <button type="button" class="btn btn-secondary" id="cancelAdd">取消</button>
                </div>
            </div>

            <script>
                $(function () {
                    // 显示添加表单
                    $('#addProductBtn').click(function () {
                        $('#overlay').show();
                        $('#addProductForm').show();
                        $(document).ready(function () {
                            $('#addProductForm h3').text('添加新商品');
                        });
                    });

                    // 隐藏添加表单（点击取消按钮或遮罩层）
                    $('#cancelAdd, #overlay').click(function () {
                        $('#overlay').hide();
                        $('#addProductForm').hide();
                        $('#addProductForm').trigger('reset'); // 清空表单
                        $('#addProductForm').removeData('productId'); // 移除缓存标识
                        $('#addProductForm button').off('click'); // 解绑提交事件
                    });

                    $('#addProductForm button').click(function () {
                        let productName = $('#newProductName').val();
                        let type = $('#newType').val();
                        let price = $('#newPrice').val();
                        let stock = $('#newStock').val();
                        let status = $('#newStatus').val();
                        let description = $('#newDescription').val();

                        console.log(productName, type, price, stock, status, description)
                        $.ajax({
                            url: 'http://localhost:8080/products',
                            type: 'Post',
                            contentType: 'application/json', // 设置内容类型
                            dataType: 'json',
                            data: JSON.stringify({ // 将对象序列化为 JSON 字符串
                                productName: productName,
                                typeId: type === "Electronics" ? 1 :
                                    type === "Clothing" ? 2 :
                                        type === "Food" ? 3 : 4,
                                price: parseFloat(price),
                                stock: parseInt(stock),
                                status: status,
                                description: description
                            }),
                            success: function (res) {
                                console.log('商品添加成功:', res);
                                alert('商品添加成功');

                                // 清空表单并隐藏
                                $('#addProductForm').trigger('reset').hide();

                                // 刷新表格数据
                                location.reload();
                            }
                        });
                    });
                });
            </script>
        </div>
    </div>
    <!-- 表格 -->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th scope="col">编号</th>
                    <th scope="col">商品名称</th>
                    <th scope="col">类型</th>
                    <th scope="col">价格</th>
                    <th scope="col">操作</th>
                </tr>
                </thead>
                <tbody>
                <script>
                    $(function () {
                        $.ajax({
                            url: 'http://localhost:8080/products',
                            type: 'get',
                            dataType: 'json',
                            success: function (res) {
                                console.log('返回的数据:', res);
                                var products = res.data;
                                products.forEach(function (product) {
                                    var tr = '<tr>' +
                                        '<th scope="row">' + product.productId + '</th>' +
                                        '<td>' + product.productName + '</td>' +
                                        '<td>' + product.typeName + '</td>' +
                                        '<td>' + product.price + '</td>' +
                                        '<td>' +
                                        '<button type="button" class="btn btn-primary">修改</button>' +
                                        '<button type="button" class="btn btn-danger">删除</button>' +
                                        '</td>' +
                                        '</tr>';
                                    $('tbody').append(tr);
                                });
                            }
                        })
                    })
                </script>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
<script>
    $(function () {
        // 删除商品功能
        $('tbody').on('click', '.btn-danger', function () {
            const $btn = $(this);
            if ($btn.data('loading')) return;
            $btn.data('loading', true);

            const productId = $btn.closest('tr').find('th').text();
            if (!confirm(`确定要删除编号为 ${productId} 的商品吗？`)) {
                $btn.data('loading', false);
                return;
            }

            $.ajax({
                url: `http://localhost:8080/products/${productId}`,
                type: 'delete',
                dataType: 'json',
                success: function (res) {
                    if (res.code === 200) {
                        location.reload(); // 直接刷新页面
                    } else {
                        alert(res.message || '删除失败');
                    }
                },
                error: function (xhr, status, error) {
                    console.error('删除请求失败:', error);
                    alert('商品删除失败，请稍后再试');
                },
                complete: function () {
                    $btn.data('loading', false);
                }
            });
        });
    });


    $(function () {
        $(document).ready(function () {
            $('#addProductForm h3').text('修改商品');
        });


        $('tbody').on('click', '.btn-primary', function () {
            const $btn = $(this);
            if ($btn.data('loading')) return;
            $btn.data('loading', true);

            const $row = $btn.closest('tr');
            const productId = $row.find('th').text().trim(); // 获取产品ID
            const productName = $row.find('td:eq(0)').text().trim(); // 第一列是商品名称
            const typeName = $row.find('td:eq(1)').text().trim();   // 第二列是类型
            const price = $row.find('td:eq(2)').text().trim();      // 第三列是价格
            const stock = $row.find('td:eq(3)').text().trim();      // 第四列是库存
            const status = $row.find('td:eq(4)').text().trim();     // 第五列是状态
            const description = $row.find('td:eq(5)').text().trim(); // 第六列是描述

            $('#newProductName').val(productName);
            $('#newType').val(typeName);
            $('#newPrice').val(price);
            $('#newStock').val(stock);
            $('#newStatus').val(status);
            $('#newDescription').val(description);

            $('#addProductForm').data('productId', productId);


            $('#overlay').show();
            $('#addProductForm').show();


            $('#addProductForm button').off('click').on('click', function () {
                let updatedProductName = $('#newProductName').val();
                let updatedType = $('#newType').val();
                let updatedPrice = $('#newPrice').val();
                let updatedStock = $('#newStock').val();
                let updatedStatus = $('#newStatus').val();
                let updatedDescription = $('#newDescription').val();
                let updatedProductId = $('#addProductForm').data('productId'); // 获取产品ID

                if (!updatedProductName || !updatedType || !updatedPrice || !updatedStock || !updatedStatus) {
                    alert('请填写所有必填字段');
                    return;
                }
                if (updatedStock < 0) {
                    alert('库存不能小于0');
                    return;
                }
                if (updatedPrice < 0) {
                    alert('价格不能小于0');
                    return;
                }

                $.ajax({
                    url: 'http://localhost:8080/products',
                    type: 'put',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({
                        productId: updatedProductId,
                        productName: updatedProductName,
                        typeId: updatedType === "Electronics" ? 1 :
                            updatedType === "Clothing" ? 2 :
                                updatedType === "Food" ? 3 : 4,
                        price: parseFloat(updatedPrice),
                        stock: parseInt(updatedStock),
                        status: updatedStatus,
                        description: updatedDescription
                    }),
                    success: function (res) {
                        console.log('商品修改成功:', res);

                        $('#addProductForm').trigger('reset').hide();
                        location.reload();
                    },
                    error: function (xhr, status, error) {
                        console.error('商品修改失败:', error);
                        alert('商品修改失败，请稍后再试');
                    },
                    complete: function () {
                        $btn.data('loading', false);
                    }
                });
            });
        });
    });
</script>
</html>